package com.hefeng.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;


public  class AliOssUtil {
    private static String endpoint = "oss-cn-guangzhou.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    private static String accessKeyId = "LTAI4G9NUVeKwrPQh9QwPyMh";
    private static String accessKeySecret = "P1NuKkn65iCM9YjunAfhCpBIN062Xg";
    // 填写Bucket名称，例如examplebucket。
    private static String bucketName = "hefengzhxf";
    private static String BucketURL="http://hefengzhxf.oss-cn-guangzhou.aliyuncs.com/";

    public OSS getOSSClient(){
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        if( ossClient.doesBucketExist(bucketName)){
        }else{
            CreateBucketRequest  bucket=new CreateBucketRequest(null);
            bucket.setBucketName(bucketName);
            bucket.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(bucket);
            ossClient.shutdown();
    }
    return ossClient;
    }
    /** 
    * 方法说明: 上传到阿里oss
    * @Param: [file, objectName] 
    * @return: java.lang.String 
    * @Author: huzh
    * @Date: 2021/10/20 
    */ 
    public String uploadFile(File file, String objectName){
        OSS oss=this.getOSSClient();
        try {
            oss.putObject(bucketName, objectName, file);
        } catch (OSSException e){
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            oss.shutdown();
        }
        return BucketURL+objectName;
    }

    public String uploadFile(InputStream file, String objectName){
        OSS oss=this.getOSSClient();
        try {
            oss.putObject(bucketName, objectName, file);
        } catch (OSSException e){
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            oss.shutdown();
        }
        return BucketURL+objectName;
    }

    public static void main(String[] args) throws IOException {
        AliOssUtil o=new AliOssUtil();
        OSS oss=o.getOSSClient();

    }


}


